<template>
  <div class="list-container">
    <el-form class="search-panel" v-model="formData" :inline="true">
      <el-form-item label-width="90px" class="search-input" label="流程名称：" prop="name" >
        <el-input v-model="queryParams.workflowName" placeholder="流程名称" clearable @clear="handleQuery"></el-input>
      </el-form-item>
      <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
      </el-form-item>
    </el-form>
    <div class="table-panel">
      <el-row class="table-operate">
        <el-button type="primary" icon="el-icon-plus" @click="addWorkflow"> 新增流程 </el-button>
      </el-row>
      <el-table :data="tableData" style="width: 100%" >
        <el-table-column type="index" label="序号" width="60" align="center">
        </el-table-column>
        <!-- <el-table-column prop="projectId" label="项目名称" min-width="150px" align="center">
        </el-table-column> -->
        <el-table-column prop="workflowName" label="流程名称" align="center" min-width="100px">
        </el-table-column>
        <el-table-column prop="corpName" label="所属劳务公司" align="center" min-width="120px">
        </el-table-column>
        <el-table-column prop="workflowRemark" label="流程说明" align="center" min-width="200px">
        </el-table-column>   
        <el-table-column  label="流程类型" align="center" min-width="130px" prop="workflowType">
        </el-table-column>
        <el-table-column prop="operation" label="操作" align="center" width="250px" fixed="right">
          <template slot-scope="scope">
            <el-button @click="checkRow(scope.row)" type="text" icon="el-icon-search">查看</el-button>
            <el-button @click="editRow(scope.row)" type="text" icon="el-icon-edit">编辑</el-button>
            <el-button @click="deleteRow(scope.row)" type="text" icon="el-icon-delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row class="page">
          <!-- <div class="page-tag">
              共{{ Math.ceil(total / pageSize) }}页/{{ total }}条数据
          </div> -->
          <!-- <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page.sync="currentPage"
              :page-sizes="[10, 20, 50]"
              :page-size="pageSize"
              layout="sizes, prev, pager, next, jumper"
              :total="total">
          </el-pagination> -->
          <pagination 
            background
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getWorkflowList"
          />
      </el-row>
    </div>
    <!--选人弹窗-->
    <el-dialog class="small-dialog"
      width="600px" 
      title="人员列表" 
      append-to-body 
      :visible.sync="dialogFormVisible"
      @close="clearUsers">
      <el-row>
        <el-col style="border-right:1px solid #e8e8e8" :span="12">
          <el-tree
            :data="treeData"
            :props="defaultProps"
            @node-click="handleNodeClick"
          ></el-tree>
        </el-col>
        <el-col :span="12">
          <!-- <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox> -->
          <!-- <div style="margin: 15px 0;"></div> -->
          <el-checkbox-group v-model="checkedUsers" @change="handlecheckedUsersChange" class="dialog-checkbox">
            <el-checkbox v-for="user in users" :label="user" :key="user.examineUserId"><p style="font-size:17px">{{ user.examineUserName }}</p></el-checkbox>
          </el-checkbox-group>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDialog">确 定</el-button>
      </div>
    </el-dialog>

    <!--新增流程弹窗-->
    <el-dialog class="small-dialog" width="1000px" :title="title" :visible.sync="visible" 
    append-to-body :close-on-click-modal="false"  @close="cancel">
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="流程名称" prop="workflowName" :rules="{required: true, message: '流程名称不能为空', trigger: 'blur'}">
          <el-input v-model="form.workflowName" :disabled="disabled" maxlength="50" show-word-limit />
        </el-form-item>
        <el-row>
          
          <el-col :span="10">
            <el-form-item label="流程类型" prop="workflowType" :rules="{required: true, message: '流程类型不能为空', trigger: 'blur'}">
              <el-select @change="changeType" style="width:100%" v-model="form.workflowType" :disabled="disabled" clearable >
                <el-option v-for="item in workflowTypeList" :key="item.code"  :label="item.name" :value="item.name"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="所属劳务公司" prop="corporation" label-width="130px" :rules="{required: true, message: '劳务公司不能为空', trigger: 'blur'}">
              <el-select style="width:100%" v-model="form.corporation" :disabled="disabled" clearable >
                <el-option v-for="item in corpList" :key="item.corporation"  :label="item.name" :value="item.corporation"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="流程说明" prop="workflowRemark">
          <el-input v-model="form.workflowRemark" :disabled="disabled" maxlength="100" show-word-limit />
        </el-form-item>
        <div style="height:30px;margin-top:-10px">
          <el-tag v-if="form.workflowType=='工资审批'" type="danger" style="margin-left:-5px">注意：工资审批流程只需要定义项目方节点，无需定义班组长和工人节点！</el-tag>
          <el-tag v-if="form.workflowType=='劳务代发审批'" type="danger" style="margin-left:-5px">注意：劳务代发审批流程只需要定义劳务公司节点！</el-tag>
        </div>
        <el-row :gutter="10">
          <el-table :data="form.nodeList" border style="width: 100%" max-height="350">
            <el-table-column prop="ser" show-overflow-tooltip width="60" label="序号">
              <template slot-scope="scope">
                <el-form-item label-width="0">
                  <span style="">{{ scope.$index + 1 }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="workflowNodeName" show-overflow-tooltip label="节点名称" width="280px">
              <template slot-scope="scope">
                <el-form-item label-width="0" :prop="'nodeList.' + scope.$index + '.'+'workflowNodeName'" :rules="{required: true, message: '节点名称不能为空', trigger: 'blur'}">
                  <el-input v-model="scope.row.workflowNodeName" :disabled="scope.row.workflowNodeName=='班组长审批'||scope.row.workflowNodeName=='工人审批'||disabled" maxlength="15" show-word-limit class="w-full" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="userList" label="审批人" width="350px">
              <template slot-scope="scope">
                <el-form-item label-width="0" :prop="'nodeList.' + scope.$index + '.'+'userList'" >
                  <el-row>
                    <el-select style="width:200px" v-model="scope.row.userList" multiple :disabled="scope.row.workflowNodeName=='班组长审批'||scope.row.workflowNodeName=='工人审批'||disabled" value-key="examineUserId" class="w-full-select">
                      <el-option v-for="item in scope.row.userList" :key="item.examineUserId" :label="item.examineUserName" :value="item" />
                    </el-select>
                    <!-- <el-input v-model="scope.row.userList"></el-input> -->
                    <el-button type="primary" :loading="loading" size="medium" style="margin-left:10px;width:100px" :disabled="scope.row.workflowNodeName=='班组长审批'||scope.row.workflowNodeName=='工人审批'||disabled" @click="onAdd(scope)">添加审批人</el-button>
                  </el-row>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" prop="caozuo" width="278">
              <template slot-scope="scope">
                <el-form-item label-width="0">
                  <el-button v-if="form.nodeList.length > 1" :disabled="scope.row.workflowNodeName=='班组长审批'||scope.row.workflowNodeName=='工人审批'||disabled" type="danger" size="medium" @click="remove(scope.$index)">移除</el-button>
                  <el-button v-if="scope.$index === form.nodeList.length -1" :disabled="disabled" type="primary" size="medium" @click="add(scope.$index)">新增节点</el-button>
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="loading" @click="visible = false">取消</el-button>
        <el-button v-if="!disabled" :loading="loading" type="primary" @click="submit">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTree,
  getPersonByTeamId,
  getPersonByserviceCorporationId,
} from "@/api/worker";
import workflowApi from "@/api/workflow/workFlow"
import { deepClone, deleteMethod } from '@/utils/common'
import tenantApi from "@/api/tenant"
import corpApi from '@/api/corp.js'
import userApi from '@/api/acl/user'
// import func from 'vue-editor-bridge';

// const userOptions = ['李建停','李健停','李建婷','李健婷','曹智超','曹志超','曹植超'];
// const userOptions = [{examineUserId: '11111',examineUserName: '李建停'},{examineUserId: '222222',examineUserName: '李建停2'}];
const userOptions = []
export default {
  data(){
    return{
      currentPage:1,
      total:0,
      tableData:[],
      pageSize:10,
      formData:{},  //搜索表单
      flag: 0,
      index: 0,
      form:{
        projectId: '',
        workflowName: '',
        workflowType: '',
        workflowStatus: '',
        workflowRemark: '',
        corporation:'',
        nodeList: [{
          workflowNodeName: '',
          userList: [
          ]
        }]
      },      //新增表单
      treeData:[{corpName: '项目方(默认)',
                  companyId: '0'}],
      defaultProps: {
        children: "children",
        label: "corpName",
      },
      disabled:false,
      readonly:false,
      loading:false,
      dialogForm:{},
      dialogFormVisible:false,  //选人弹窗
      visible:false,            //新增弹窗
      checkAll: false,
      users:userOptions,
      checkedUsers:[],
      isIndeterminate: true,
      title:'新增流程',
      workflowTypeList:[
      ],
      corpList:[],
      workflowStatusList:[
        {
          code:1,
          text:'开启'
        },{
          code:2,
          text:'关闭'
        }
      ],
      defaultCheckedItems:[
      ],
      rules: {
        workflowName: [
          { required: true, message: '请填写流程名称', trigger: 'blur' }
        ],
        workflowStatus: [
          { required: true, message: '请选择流程状态', trigger: 'blur' }
        ],
        corporation: [
          { required: true, message: '请选择劳务公司', trigger: 'blur' }
        ]
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        workflowName:''
      },
      category:'2',
      currentPage: 1,
      limit:10,
      isAdmin:'0',   //0-非超管账号，1-超管账号
      formData: {}, // 查询表单对象
    }
  },
  created(){
    this.getWorkflowList()
    // this.fetchData()
    this.getWorkflowType()
    this.getCorpList()
  },
  methods:{
    changeType(row){
      if(row=='工资审批'){
        this.form.workflowName= '工资审批流程',
        this.form.workflowRemark= '由劳务公司提交，班组长工人及项目方审批的工资审批流程'
      }else if(row=='劳务代发审批'){
        this.form.workflowName= '劳务代发审批流程',
        this.form.workflowRemark= '由项目方提交，劳务公司审批的劳务代发审批流程'
      }else{
        this.form.workflowName= '',
        this.form.workflowRemark= ''
      }
    },
    fetchData() {
      // console.log("-------")
      tenantApi.getTenantList2(this.currentPage, this.limit, this.category, this.isAdmin,this.formData).then(response => {
          // 数据加载并绑定成功
          let date = response.data.items
          let datas = []
          // console.log(date)
          date.forEach(function(e) {
            datas.push({examineUserId:e.id,examineUserName:e.nickName})
          })
          this.users = datas
        }
      )
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getWorkflowList();
    },
    getWorkflowList() {
        workflowApi.getTableListWorkflow(this.queryParams).then(res => {
          this.total = res.data.length
          this.tableData = res.data
        })
    },
    // 树状图
    handleNodeClick(row) {
      userApi.selectUsersByCompanyId(row.companyId).then(res=>{
        // console.log(res);
        let date = res.data.userList
        let datas=[]
        date.forEach(function(e){
          datas.push({examineUserId:e.id,examineUserName:e.nickName})
        })
        this.users = datas
      })
      
      // if (res.children == null) {
      //   // console.log("班组")
      //   this.flag = 0;
      //   this.searchForm.team_id = res.id;
      //   this.searchForm.service_corporation_id = null;
      //   this.getCheckbox();
      // } else {
      //   this.flag = 1;
      //   this.searchForm.service_corporation_id = res.id;
      //   this.searchForm.team_id = null;
      //   this.getCheckbox();
      // }
    },
    getCheckbox(){},
    addWorkflow() {
      this.disabled = false
      this.visible = true;
    },
    submit(){
      this.loading = true
      this.$refs.form.validate(valid => {
        if (valid) {
          // let date = this.deepClone(this.form)
          this.form.workflowStatus = 1
          let date = this.form

          // console.log(this.checkedUsers)
          // date.nodeList.forEach(element => {
          //   element.userList.forEach(ele => {
          //     this.$set(ele, 'examineUserId', ele.examineUserId)
          //   })
          // })
          // console.log("=========");
          // console.log(date);
          date.nodeList.forEach(function(item,index) {
            // console.log(item.userList.length);
            if(item.userList.length == 0) {
              item.userList.push(
                {'examineUserId': '0'}
              )
            }
          })
          // console.log(date);

          workflowApi.saveWorkflow(date).then(() => {
            this.loading = false
            this.cancel()
            this.getWorkflowList()
          }).catch(() => {
            this.$alert(this.form.workflowType + '类型流程已存在，请在该页面修改该类型流程', '警告', {
            confirmButtonText: '确定',
            // callback: action => {
            //   this.$message({
            //     type: 'info',
            //     message: `action: ${ action }`
            //   });
            // }
            });
            this.loading = false
          })

        } else {
          this.loading = false
        }
      })
      // this.$router.push('/system/workflow/')

    },
    onSubmit(){},
    confirmDialog(){
      this.form.nodeList[this.index].userList = this.checkedUsers
      this.dialogFormVisible = false
      this.checkedUsers = []
      this.users = []
    },
    handleCheckAllChange(val) {
      this.checkedUsers = val ? userOptions : [];
      this.isIndeterminate = false;
    },
    handlecheckedUsersChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.users.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.users.length;
    },
    cancel() {
      this.form = {
        projectId: '1',
        workflowName: '',
        workflowType: '',
        workflowStatus: '',
        workflowRemark: '',
        nodeList: [{
          workflowNodeName: '',
          userList: []
        }]
      }
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
      this.visible = false
    },
    //添加人员
    onAdd(data) {
      // console.log(data.$index);
      this.index = data.$index
      this.dialogFormVisible = true

      this.treeData = [{corpName: '项目方(默认)',
                  companyId: '0'}]
      var treeData = this.treeData
      if(this.form.workflowType == '劳务代发审批') {
        treeData = []
      }
      
      if(this.form.workflowType != '工资审批') {
        this.corpList.forEach(function(item,index) {
          treeData.push({corpName: item.name, companyId: item.corporation})
        })
        this.treeData = treeData
      }
      
    },

    //移除节点
    remove(index){
      this.form.nodeList.splice(index, 1)
    },
    //新增节点
    add(){
      this.form.nodeList.push(
        {
          // ser: this.form.nodeList.length + 1,
          workflowNodeName: '',
          userList: []
        }
      )
      // console.log(this.form);
    },
    getList(){},
    handleSizeChange(val){
      this.pageSize=val
      this.getList()
    },
    //currentPage当前页改变时
    handleCurrentChange(val) {
      this.currentPage=val
      this.getList()
    },
    changeEnable(data){
      // console.log(data);
      // workflowApi.changeEnable(data.id).then(res => {
      //   if(res.code === 200){
      //     this.$message({
      //           type: "success",
      //           message: '修改成功',
      //         });
      //   }
      // })
    },
    deleteRow(data) {
      // console.log(data.workflowId);
      this.$confirm('确定删除【' + [data.workflowName] +'】流程？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
         workflowApi.deleteWorkflow([data.workflowId])
         this.getWorkflowList()
      })
      
      // this.handleQuery()
    },
    checkRow(data){
      this.visible=true
      let id = data.workflowId
      workflowApi.getWorkflowInfo(({workflowId:id})).then(res => {
        this.form = res.data
        this.title = '查看'
        this.disabled = true
      })
    },
    editRow(data) {
      this.visible=true
      let id = data.workflowId
      workflowApi.getWorkflowInfo(({workflowId:id})).then(res => {
        console.log(res);
        this.form = res.data
        this.title = '编辑'
        this.disabled = false
      })
    },
    getWorkflowType() {
      workflowApi.getWorkflowType().then(res => {
        this.workflowTypeList = res.data.workType
        // console.log(this.workflowTypeList);
      })
    },
    getCorpList() {
      // var treeData = this.treeData
      corpApi.listByProjectId().then(res => {
          let date = res.data.data.records
          let data = []
          date.forEach(function(item,index) {
              data.push({name: item.name, corporation: item.serviceCorporationId+''})
              // treeData.push({corpName: item.name, companyId: item.serviceCorporationId+''})
          })
          this.corpList = data
          // this.treeData = treeData
      })
      
    },
    clearUsers() {
      this.users = []
    }
  }
}
</script>

<style lang="scss">
.dialog-checkbox{
  .el-checkbox{
    display: block;
    margin-left: 20px;
  }
}
</style>
